package com.businesswebsite.businesswebsite.FormalWebExplot.Service.impl;

import com.businesswebsite.businesswebsite.FormalWebExplot.Entity.Product;
import com.businesswebsite.businesswebsite.FormalWebExplot.Service.Utils.FileUploadTool;
import com.businesswebsite.businesswebsite.FormalWebExplot.Utils.Renum;
import com.businesswebsite.businesswebsite.FormalWebExplot.Utils.Result;
import com.businesswebsite.businesswebsite.FormalWebExplot.Utils.ResultUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@Service
public class FileUploadToolImpl implements FileUploadTool {
    @Value("${spring.file.upload.path}")
    private String Path;
    @Override
    public Result<String> fileUpLoad(MultipartFile file,String pro_id) {
        if (file.isEmpty()){
            return ResultUtil.error(Renum.DATA_IS_NULL.getCode(), Renum.DATA_IS_NULL.getMsg());
        }
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = pro_id+"."+originalFilename.substring(originalFilename.lastIndexOf(".")+1);//拼接文件名
        String filePath = Path;
        File dest = new File(filePath+fileName);
        if(!dest.getParentFile().exists())
            dest.getParentFile().mkdirs();
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            ResultUtil.error(Renum.UNKNOWN_ERROR.getCode(),"上传文件出错，请重试");
        }
        return ResultUtil.success("文件上传成功:"+fileName);
    }

}
